<template>
  <a-modal
    :title="formTile + '模板消息引用标签'"
    :visible="true"
    width="60%"
    :footer="null"
    @cancel="reset"
  >
    <div class="main">
      <a-card>
        <a-row
          type="flex"
          justify="start"
          align="top"
        >
          <a-col :span="24">
            <a-form
              :form="form"
              @submit="handleSubmit"
              :labelCol="formItemLayout.labelCol"
              :wrapperCol="formItemLayout.wrapperCol"
            >
              <a-form-item
                label="标签主题"
                :required="true"
              >
                <a-input
                  allow-clear
                  placeholder="请输入标签主题"
                  v-decorator="[
                  `name`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入标签名称'
                      },
                    ]
                  }
                ]"
                />
              </a-form-item>
              <a-form-item
                label="查询数据源"
                :required="true"
              >
                <a-select
                  allow-clear
                  show-search
                  placeholder="请选择查询数据源"
                  optionFilterProp="children"
                  @change="onchange"
                  v-decorator="[
                  'datasourceId',
                  {
                    rules: [{ required: true, message: '请选择查询数据源!' }]
                  }
                ]"
                >
                  <a-select-option
                    :value="item.id"
                    v-for="(item,index)  in menuType"
                    :key="index"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item
                label="标签类型"
                :required="true"
              >
                <a-select
                  allow-clear
                  show-search
                  placeholder="请选择标签类型"
                  optionFilterProp="children"
                  @change="changetype"
                  v-decorator="[
                  'type',
                  {
                    rules: [{ required: true, message: '请选择标签类型!' }]
                  }
                ]"
                >
                  <a-select-option
                    :value="item.id"
                    v-for="(item,index)  in labelType"
                    :key="index"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="标签描述">
                <a-textarea
                  allow-clear
                  placeholder="请输入标签描述"
                  v-decorator="['desc', { rules: [{ required: true, message: '请输入标签描述' }] }]"
                ></a-textarea>
              </a-form-item>
              <a-form-item
                label="查询SQL语句"
                v-if="type == 1"
              >
                <div class="button">
                  <a-button @click="check">检验SQL</a-button>
                </div>
                <a-textarea
                  allow-clear
                  :rows="8"
                  placeholder="请输入查询SQL语句"
                  v-decorator="['sqlStr', { rules: [{ required: true, message: '请输入查询SQL语句' }] }]"
                ></a-textarea>
              </a-form-item>
              <a-form-item label="字段标签栏">
                <div
                  style="border: 1px solid #d9d9d9;height: 100px;padding: 20px;"
                  v-if="type == 1"
                >
                  <span
                    v-for="(item,index) in fieldList"
                    :key="index"
                  >
                    <a-tag color="blue" v-if="add">
                       {{'${'+item.column+'}'}}
                    </a-tag>
                     <a-tag color="blue" v-else>
                       {{item.column}}
                    </a-tag>
                  </span>
                </div>
                <div
                  style="border: 1px solid #d9d9d9;height: 200px;padding: 20px;"
                  v-else
                >
                  <template v-for="(tag, index) in tags">
                    <a-tag
                      color="blue"
                      :key="index"
                      :closable="true"
                      @close="() => handleClose(tag.name)"
                    >
                      {{ tag.name }}
                    </a-tag>
                  </template>
                 <div v-if="inputVisible">
                 <div>  <span>标签名称：</span>
                  <a-input
                    v-if="inputVisible"
                    ref="input"
                    type="text"
                    size="small"
                    :style="{ width: '200px' }"
                    :value="inputValue"
                    @change="handleInputChange"
                  /></div>
                 <div><span> 标签描述：</span>
                   <a-input
                    ref="input"
                    type="text"
                    size="small"
                    :style="{ width: '200px' }"
                    :value="inputContent"
                    @change="inputChange"
                    style="margin-right:5px"
                  /></div>
                  <a-button @click="handleInputConfirm" type="primary">确定</a-button>
                 </div>
                  <a-tag
                    v-else
                    style="background: #fff; borderStyle: dashed;"
                    @click="showInput"
                  >
                    <a-icon type="plus" /> New Tag
                  </a-tag>
                  
                </div>
              </a-form-item>
              <a-row style="margin-top:10px">
                <a-col
                  :span="16"
                  :offset="18"
                  class="info-action"
                >
                  <a-button @click="clear">
                    重置
                  </a-button>
                  <a-button
                    :style="{ marginLeft: '8px' }"
                    type="primary"
                    html-type="submit"
                    :loading="loading"
                  >
                    保存
                  </a-button>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>
      </a-card>
    </div>

  </a-modal>
</template>

<script>
import { postAction, getAction } from '@/api/manage'
const labelType = [
  {
    id: 1,
    name: '模板消息标签'
  },
  {
    id: 2,
    name: '手动创建模板标签'
  }
]
export default {
  props: {
    content: {
      type: Object,
      default: null
    },
    appid: {
      type: String,
      default: null
    }
  },

  data() {
    return {
      urlKey: 'basemgt-wx',
      labelType,
      menuType: [],
      fieldList: [],
      dbType: '',
      id: '',
      tags: [],
      placeholderDetailList: [],
      type: 1,
      inputVisible: false,
      inputValue: '',
      inputContent:'',
      datasourceId: '',
      formItemLayout: {
        labelCol: {
          xl: { span: 5 },
          xs: { span: 5 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xl: { span: 14 },
          xs: { span: 14 },
          sm: { span: 14 }
        }
      },
      loading: false,
      form: this.$form.createForm(this),
      add: false
    }
  },

  created() {
    const { content } = this.$props
    console.log(content)
    if (content) {
      this.formTile = '编辑'
      this.id = content.id
      this.type = content.type
      this.$nextTick(() => {
        this.form.setFieldsValue({
          type: content.type,
          name: content.name,
          datasourceId: content.datasourceId,
          desc: content.describe,
          sqlStr: content.sqlStatement
        })
      })
      this.getDetailList()
    } else {
      this.formTile = '新增'
      this.add = true
    }
  },
  watch: {
    appid() {
      this.getMenuList()
    }
  },
  mounted() {
    this.getMenuList()
  },
  methods: {
    handleClose(removedTag) {
      // this.tags.map((item,index)=>{
      //   if(item.name == removedTag){
      //     this.tags.splice(index, 1)
      //   }
      // })
      this.tags.filter(tag => tag.name !== removedTag)
    },

    showInput() {
      this.inputVisible = true
    },

    handleInputChange(e) {
      e.preventDefault()
      this.inputValue = e.target.value
    },
    inputChange(e) {
      e.preventDefault()
      this.inputContent = e.target.value
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      const inputContent = this.inputContent
      let tags = this.tags
      if (inputValue && tags.indexOf(inputValue) === -1) {
        const tag = {
          name:'${' + inputValue +'}',
          desc:inputContent
        }
        tags = [...tags, tag]
      }
      Object.assign(this, {
        tags,
        inputVisible: false,
        inputValue: '',
        inputContent:'',
      })
    },
    reset() {
      this.form.resetFields()
      this.fieldList = []
      this.$emit('close')
    },
    clear() {
      this.form.resetFields()
      this.fieldList = []
    },
    onchange(values) {
      this.menuType.map(item => {
        if (values == item.id) {
          this.dbType = item.remark
        }
      })
    },
    changetype(type) {
      this.type = type
    },
    getMenuList() {
      const params = {}
      getAction(`${this.urlKey}/WxPlaceHolder/findDataSourceInfo`, params).then(data => {
        if (data.code == 200) {
          this.menuType = data.data
        } else {
          this.$message.warning(data.msg || data.message)
        }
      })
    },
    getDetailList() {
      const params = {
        id: this.id
      }
      getAction(`${this.urlKey}/WxPlaceHolder/findWxPlaceHolderDetailById`, params).then(data => {
        if (data.code == 200) {
          if (this.type == 1) {
            const arr = []
            data.data.placeholderDetailList.map(item => {
              const subitem = {
                aliasName: item.topicTagName,
                column: item.fieldName
              }
              arr.push(subitem)
            })
            this.fieldList = arr
          } else {
            data.data.placeholderDetailList.map(item => {
              const obj = {
                 name:item.fieldName,
                 desc:item.describe
              }
              this.tags.push(obj)
            })
          }
        } else {
          this.$message.warning(data.msg || data.message)
        }
      })
    },
    check() {
      this.fieldList = []
      this.form.validateFields((err, values) => {
        if (!err) {
          const params = {
            sqlStr: values.sqlStr,
            id: values.datasourceId,
            dbType: this.dbType
          }
          postAction(`${this.urlKey}/WxPlaceHolder/checkSqlScript`, params).then(data => {
            if (data.code == 200) {
              this.fieldList = data.data.parseSqlDTO.fieldList
              if (data.data.textMsg) {
                this.$message.warning(data.data.textMsg)
              }
            } else {
              this.$message.warning(data.data.textMsg)
            }
          })
        }
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.submit(values)
        }
      })
    },
    submit(values) {
      if (this.type == 1) {
        if (this.fieldList && this.add) {
          this.fieldList.map(item => {
            if (item.aliasName) {
              const content = {
                topicTagName: item.aliasName,
                fieldName: '${' + item.column +'}'
              }
              this.placeholderDetailList.push(content)
            } else {
              const content = {
                topicTagName: item.column,
                fieldName: '${' + item.column +'}'
              }
              this.placeholderDetailList.push(content)
            }
          })
        }else{
          this.fieldList.map(item => {
            if (item.aliasName) {
              const content = {
                topicTagName: item.aliasName,
                fieldName: item.column
              }
              this.placeholderDetailList.push(content)
            } else {
              const content = {
                topicTagName: item.column,
                fieldName: item.column
              }
              this.placeholderDetailList.push(content)
            }
          })
        }
      } else {
        if (this.tags) {
          this.tags.map(item => {
            const content = {
              topicTagName: item.name,
              fieldName: item.name,
              describe:item.desc
            }
            this.placeholderDetailList.push(content)
          })
        }
      }
      var params = {
        name: values.name,
        appid: this.appid,
        datasourceId: values.datasourceId,
        describe: values.desc,
        sqlStatement: values.sqlStr,
        type: values.type,
        placeholderDetailList: this.placeholderDetailList
      }
      if (this.id) {
        ;(params.tagId = this.tagId), (params.id = this.id)
      }
      if (!params.placeholderDetailList.length && this.type == 1) {
        this.$message.warning('请先校验SQL！')
      } else {
        const api = this.add ? `${this.urlKey}/WxPlaceHolder/insertWxPlaceHolder` : `${this.urlKey}/WxPlaceHolder/updateWxPlaceHolder`
        postAction(api, params).then(data => {
          if (data.code == 200) {
            this.$message.success(this.add ? '新建成功！' : '修改成功！')
            this.reset()
          } else {
            this.$message.warning(data.msg || data.message)
          }
        })
      }
    }
  }
}
</script>
<style scoped>
.button {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 5px;
}
</style>
<style>
#sqlStr{
      font-weight: 500;
    font-size: 16px;
}
</style>

